
#include "systick.h"
#include "buzzer_ctrl.h"
#include "gpio.h"


STR_BUZZER_HDL buzzerHdl[BUZZER_ALL];


/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/

void buzzer_param_set(ENUM_BUZZER_NUM num, uint16_t times, uint16_t holdtime)
{
	STR_BUZZER_HDL *buzzer_hdl = &buzzerHdl[num];	
	
	if(num >= BUZZER_ALL)
	{
		return;
	}

	buzzer_hdl->beep_times = times;
	buzzer_hdl->beep_holdtime = holdtime;
}


/*!
    \brief      
    \param[in]  none
    \param[out] none
    \retval     none
*/


uint8_t buzzer_beep_ctrl(ENUM_BUZZER_NUM num)
{
	STR_BUZZER_HDL *buzzer_hdl = &buzzerHdl[num];	
	
	if(num >= BUZZER_ALL)
	{
		return 0;
	}
	
	buzzer_hdl->now_time = (uint16_t)get_system_runingtime();
		
	switch(buzzer_hdl->FSM)
	{
		case BUZZER_IDLE:
			
			if((buzzer_hdl->beep_times != 0) && (buzzer_hdl->beep_holdtime != 0))
			{				
				buzzer_hdl->beep_cnt = 0;
				
				buzzer_hdl->FSM = BUZZER_BEEP;
				buzzer_hdl->exe_time = (uint16_t)get_system_runingtime();
			}
			
			buzzer_hdl->gpio_output = 0;
		
			break;
		
		case BUZZER_BEEP:
			
			if(buzzer_hdl->beep_cnt < buzzer_hdl->beep_times)
			{				
				buzzer_hdl->gpio_output = 1;
				if((buzzer_hdl->now_time - buzzer_hdl->exe_time) > buzzer_hdl->beep_holdtime)
				{
					buzzer_hdl->beep_cnt++;
					buzzer_hdl->FSM = BUZZER_STOP;
					buzzer_hdl->exe_time = (uint16_t)get_system_runingtime();
				}
			}
			else
			{
				buzzer_hdl->gpio_output = 0;
				buzzer_hdl->FSM = BUZZER_IDLE;
				
				buzzer_hdl->beep_cnt = 0;
				buzzer_hdl->beep_times = 0;
				buzzer_hdl->beep_holdtime = 0;
			}
		
			break;
		
		case BUZZER_STOP:
			
			if((buzzer_hdl->now_time - buzzer_hdl->exe_time) > buzzer_hdl->beep_holdtime)
			{
				buzzer_hdl->FSM = BUZZER_BEEP;
				buzzer_hdl->exe_time = (uint16_t)get_system_runingtime();
			}
			
			buzzer_hdl->gpio_output = 0;
		
			break;
		
		
		default:
			break;
	}
		
	return buzzer_hdl->gpio_output;

}

